#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by PyCharm.
# @Project: Code_Clone_Detection_Educoder
# @File: app.py
# @Description:
# @Time: 2018/12/15 16:56
# @Author: ljz

import uuid

from flask import Flask, jsonify, request
from celery import Celery

from utils import get_class_result, get_single_student_result, operate_task_status
from CCDetector import clone_detector, code_fingerprint

app = Flask(__name__)
app.config['CELERY_BROKER_URL'] = 'redis://127.0.0.1:6379'

celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)


@celery.task
def detect(language, user_data, query_id):
    operate_task_status.set_is_running(query_id)
    clone_detector.run(code_fingerprint.parse_json(language, user_data, query_id), query_id)
    operate_task_status.set_is_completed(query_id)


@app.route('/api/v1/check_codes', methods=['POST'])
def check_codes():
    supported_language = ['java', 'python']
    user_data = request.values.get('user_data')
    language = request.values.get('language')
    if user_data == '' or user_data is None:
        response = {'status': 1,
                    'msg': 'missing query_data',
                    'query_id': ''}
    elif language == '' or language is None:
        response = {'status': 1,
                    'msg': 'missing language',
                    'query_id': ''}
    elif language not in supported_language:
        response = {'status': 1,
                    'msg': 'language is not supported',
                    'query_id': ''}
    else:
        query_id = uuid.uuid1()
        try:
            detect.delay(language, user_data, query_id)
        except Exception as e:
            response = {'status': 1,
                        'msg': str(e),
                        'query_id': ''}
        else:
            response = {'status': 0,
                        'msg': '',
                        'query_id': query_id}
    return jsonify(response)


@app.route('/api/v1/check_lists', methods=['POST'])
def check_lists():
    query_id = request.values.get('query_id')
    if query_id == '' or query_id is None:
        response = {'status': 1,
                    'msg': 'missing query_id',
                    'user_lists': None}
    else:
        if operate_task_status.check_is_completed(query_id) == 'completed':
            try:
                user_lists = get_class_result.run(query_id)
            except Exception as e:
                response = {'status': 1,
                            'msg': str(e),
                            'user_lists': None}
            else:
                response = {'status': 0,
                            'msg': '',
                            'user_lists': user_lists}
        elif operate_task_status.check_is_completed(query_id) == 'not completed':
            response = {'status': 2,
                        'msg': 'the task({}) is still running'.format(query_id),
                        'user_lists': None}
        else:
            response = {'status': 1,
                        'msg': 'the task({}) does not exist'.format(query_id),
                        'user_lists': None}
    return jsonify(response)


@app.route('/api/v1/check_info', methods=['POST'])
def check_info():
    query_id = request.values.get('query_id')
    user_id = request.values.get('user_id')
    if query_id == '' or query_id is None:
        response = {'status': 1,
                    'msg': 'missing query_id',
                    'code_info': None}
    elif user_id == '' or user_id is None:
        response = {'status': 1,
                    'msg': 'missing user_id',
                    'code_info': None}
    else:
        if operate_task_status.check_is_completed(query_id) == 'completed':
            try:
                code_info = get_single_student_result.run(query_id, user_id)
            except Exception as e:
                response = {'status': 1,
                            'msg': str(e),
                            'code_info': None}
            else:
                response = {'status': 0,
                            'msg': '',
                            'code_info': code_info}
        elif operate_task_status.check_is_completed(query_id) == 'not completed':
            response = {'status': 2,
                        'mag': 'the task({}) is still running'.format(query_id),
                        'code_info': None}
        else:
            response = {'status': 1,
                        'msg': 'the task({}) does not exist'.format(query_id),
                        'code_info': None}
    return jsonify(response)


if __name__ == '__main__':
    app.run()
